package com.sxt.demo.djiapplication.activity;

import static com.sxt.demo.djiapplication.common.CommonConstants.ERROR_TRACE;
import static com.sxt.demo.djiapplication.exceptionhandler.CrashHandler.ERROR_TRACE_PATH;

import android.content.Intent;
import android.view.KeyEvent;

import com.sxt.demo.djiapplication.R;
import com.sxt.demo.djiapplication.exceptionhandler.CrashHandler;
import com.sxt.demo.djiapplication.utils.FileUtil;
import com.xuexiang.xui.utils.KeyboardUtils;
import com.xuexiang.xui.widget.activity.BaseSplashActivity;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import kotlin.Pair;

/**
 * 渐近式启动页
 *
 * @author xuexiang
 * @since 2018/11/27 下午5:24
 */
public class SplashActivity extends BaseSplashActivity {

    private boolean hasNewestErrorTrace;

    private File errorTraceCache;

    @Override
    protected long getSplashDurationMillis() {
        return 500;
    }

    @Override
    public void onCreateActivity() {
        initSplashView(R.drawable.splash);
        startSplash(true);
        checkHasErrorTrace();
    }

    @Override
    public void onSplashFinished() {
        Intent intent = new Intent(this, ConnectionActivity.class);
        if (hasNewestErrorTrace) {
            intent.putExtra(ERROR_TRACE, errorTraceCache);
        }
        startActivity(intent);
        finish();
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return KeyboardUtils.onDisableBackKeyDown(keyCode) && super.onKeyDown(keyCode, event);
    }

    /**
     * 检查app是否存在错误(异常)记录
     */
    private void checkHasErrorTrace() {
        Pair<Boolean, List<File>> existsFile = FileUtil.isFileExistsWithSuffix(getFilesDir().getParent()
                + File.separator + ERROR_TRACE_PATH, CrashHandler.FILE_NAME_SUFFIX);
        File trace = getNewestTrace(existsFile.getSecond());
        if (existsFile.getFirst() && trace != null) {
            hasNewestErrorTrace = true;
            errorTraceCache = new File(getCacheDir() + File.separator + trace.getName());
            FileUtil.copyFile(trace, errorTraceCache);
            FileUtil.rename(trace, "_" + trace.getName());
        }
    }

    /**
     * 获取最新的日志文件
     *
     * @return 最新的日志文件
     */
    private File getNewestTrace(List<File> files) {
        if (files.isEmpty()) {
            return null;
        }
        if (files.size() == 1) {
            File trace = files.get(0);
            return trace.getName().startsWith("_") ? null : trace;
        }
        List<File> tmp = new ArrayList<>(files.size());
        for (File file : files) {
            if (!file.getName().startsWith("_")) {
                tmp.add(file);
            }
        }
        if (tmp.size() == 0) {
            return null;
        }
        File[] array = tmp.toArray(new File[0]);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Arrays.sort(array, (first, second) -> {
                    try {
                        Date firstDate = dateFormat.parse(FileUtil.getFileName(first));
                        Date secondDate = dateFormat.parse(FileUtil.getFileName(second));
                        if (firstDate == null || secondDate == null) {
                            return 0;
                        }
                        return secondDate.compareTo(firstDate);
                    } catch (ParseException e) {
                        return 0;
                    }
                }
        );
        File trace = array[0];
        return trace.getName().startsWith("_") ? null : trace;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
